﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utils;
using Bll;

namespace Analysis.Controllers.PCController
{
    public class LoginController : Controller
    {
        // GET: PCHome
        public ActionResult Index()
        {
            return View();
        }


        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            string requestURL = requestContext.HttpContext.Request.Url.ToString();

            if (!requestURL.Contains("/Login/"))
            {
                HttpSessionStateBase session = requestContext.HttpContext.Session;
                if (session==null||session["userName"] == null)
                {
                    //去登陆
                   requestContext.HttpContext.Response.Redirect("/Login/LoginPage?url=" + requestURL);
                }
            }

            base.Initialize(requestContext);
        }


        /// <summary>
        /// 登录页面
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult LoginPage(string url=null)
        {
            if (!string.IsNullOrEmpty(url))
            {
                ViewBag.redirectUrl = url;
            }

            return View();
        }

        /// <summary>
        /// 登录操作
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public JsonResult LoginAction(string userName, string password, string redirectUrl = "/TestAdminLET/TestEchart")
        {
            string flag = "0";
            string temp = Encryption.EncryptMD5(password);

            string sql = "select count(*) from [user] where accountName='" + userName + "' and Effected=1";
            int num=  BllBBCCommon.GetCountBySQL("user", sql);
            if (num > 0)
            {
                string sql2 = "select accountPassword as cs from [user] where accountName='" + userName + "' and Effected=1 ";
                object obj=BllBBCCommon.SelectSingleValueBySql("user",sql2);
                string accountPassword = obj == null ? "" : obj.ToString();
                if (string.IsNullOrEmpty(accountPassword) || temp != accountPassword)
                {
                    flag = "-1";  //密码不正确
                }
                else
                {
                    Session["userName"] = userName;
                    flag = redirectUrl;
                }
            }
            else
            {
                flag = "-2"; //查无此用户
            }

            return Json(flag, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 退出操作
        /// </summary>
        /// <returns></returns>
        public void Logout()
        {
            Session["userName"] = null;
        }
    }
}